#!/usr/bin/env python
# coding=utf-8


import os
import sys
import re
import time
import struct


def print_data_file(filename):
	# file struct
	fileStruct = {'Version': '',
			# Date (year, month, day, hour, minute, second, ms)
			'Date': (),
			'Declaration': '',
			'OffsetToData': 0,
			'Records': {}
			}
	f = open(filename, 'rb')
	fileStruct['Version'] = f.read(4)
	def BCD2N(c):
		return int(hex(ord(c))[2:])
	b8s = map(BCD2N, f.read(8))
	fileStruct['Date'] = (b8s[0]*100 + b8s[1],) + tuple(b8s[2:])
	fileStruct['Declaration'] = f.read(4)
	def BIN2DW(s):
		return struct.unpack('>I', s)[0]
	def B2N(s):
		return struct.unpack('>B', s)[0]
	rn = BIN2DW(f.read(4))
	offset = BIN2DW(f.read(4))
	assert(offset == 24)
	fileStruct['OffsetToData'] = offset
	
	# print
	print('Data Version: %(Version)s' % fileStruct)
	print('Data Created Date: %d-%d-%d %d:%d:%d %d*10ms' % fileStruct['Date'])
	print('Data Declaration: %(Declaration)s' % fileStruct)
	print('MultiESR Data Record Number: %d' % (rn,))
	print('Offset to MulESR Data: %(OffsetToData)d' % fileStruct)
	print('')

	ids = []
	offsets = []
	for n in range(rn):
		ids.append(BIN2DW(f.read(4)))
		offsets.append(BIN2DW(f.read(4)))
	for n in range(rn):
		id = ids[n]
		offset = offsets[n]
		f.seek(offset)
		recordSize = B2N(f.read(1))
		strNum = B2N(f.read(1))
		ss = f.read(recordSize - 1)
		assert(ss[-1] == '\0')
		ss = ss[:-1]
		strs = ss.split(' / ')

		assert(len(strs) == strNum)
		assert(not fileStruct['Records'].has_key(id))
		fileStruct['Records'][id] = tuple(strs)

		# print 
		print('MultiESR Data Record No.%d' % (n+1,))
		print('MultESR Data Record ID: %d' % (id,))
		print('Offset to MultESR Data: %d' % (offset,))
		print('ESR Number: %d' % (strNum,))
		for nn in range(strNum):
			print('ESR1: %s' % (strs[nn],))
		print('')


def main():
	if len(sys.argv) != 2:
		print('Usage:')
		print('MltPhonemeView.py inputfile')
		return
	print_data_file(sys.argv[1])

if __name__ == '__main__':
	main()


